package aole.excel;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileChooser extends JPanel implements ActionListener {
	private static final long			serialVersionUID	= 1L;
	private File						file;
	private ArrayList< ActionListener >	listeners;
	private String						actionCmd;
	private JTextField					txtPath;

	public FileChooser() {
		super( new BorderLayout() );
		listeners = new ArrayList<>();

		txtPath = new JTextField( 20 );
		txtPath.setEditable( false );
		txtPath.setText( "No file selected." );
		add( txtPath, BorderLayout.CENTER );

		JButton btn = new JButton( "..." );
		btn.addActionListener( this );
		add( btn, BorderLayout.EAST );
	}

	public FileChooser( File f ) {
		this();

		file = f;
		txtPath.setText( f.getPath() );
	}

	@Override
	public void actionPerformed( ActionEvent e ) {
		final JFileChooser fc = new JFileChooser( file );
		int returnVal = fc.showOpenDialog( this );
		if( returnVal == JFileChooser.APPROVE_OPTION ) {
			file = fc.getSelectedFile();
			txtPath.setText( file.getPath() );

			ActionEvent ev = new ActionEvent( this,
					ActionEvent.ACTION_PERFORMED, actionCmd );
			for( ActionListener l: listeners ) {
				l.actionPerformed( ev );
			}
		}
	}

	public void setActionCommand( String cmd ) {
		actionCmd = cmd;
	}

	public void addActionListener( ActionListener l ) {
		listeners.add( l );
	}

	public void removeActionListener( ActionListener l ) {
		listeners.remove( l );
	}

	public File getFile() {
		return file;
	}

	public void setFile( File f ) {
		file = f;
		txtPath.setText( f.getPath() );
	}
}
